package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截
 */
public class CheckLoginInterceptor implements HandlerInterceptor{

    @Autowired
    private IUserInfoRedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

        System.out.println(request.getRequestURL());
        System.out.println(request.getMethod());
        //放开静态和option
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //handler 请求映射方法的处理器
        /**
         * springmvc启动时候回会将所有的请求映射方法解析,并封装成一个对象
         * HandlerMethod:这个对象里面包换了请求映射方法所有信息:包括映射方法上的注解
         *2,springmvc定义一个类似map对象管理将所有的请求映射方法对象,进行统一管理,
         *  map{
         *      map的key是请求映射方法的url路径,value就是请求映射方法对象
         *      "/users/getCurrentUser"---handlerMethod
         *  }
         *3,浏览器发起请求时,输入url地址
         *  服务器解析url地址获取/users/getCurrentUser,进而获取该映射方法路径url对应的映射对象
         *  :handlerMethod
         *  4,springmvc马上调用 checkLoginInterceptor类对象,执行*/

        //1:识别请求映射方法是否贴有@RequireLogin
        HandlerMethod hm = (HandlerMethod) handler;
        //获取token,判断登录
        //所有方法有登录,都延长30分钟
        String token = request.getHeader("token");
        UserInfo user = redisService.getUserByToken(token);
        if(hm.hasMethodAnnotation(RequireLogin.class)){
            if(user == null){
                //返回失败之前要返回数据,告诉浏览器失败了
                response.setContentType("application/json;charset:utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        /*if(user == null){
            //返回失败之前要返回数据,告诉浏览器失败了
            response.setContentType("application/json;charset:utf-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }*/
        return true;
    }
}
